// 管理用户数据相关

import { defineStore } from "pinia";
import { ref } from "vue";
import { loginAPI, registerAPI, getUserInfoAPI ,codeLoginAPI} from "@/apis/user";
import { useCartStore } from "./cartStore";
import { mergeCartAPI } from "@/apis/cart";
export const useUserStore = defineStore(
  "user",
  () => {
    const cartStore = useCartStore();
    // 1. 定义管理用户数据的state
    const userInfo = ref({});
    let userToken = ref({});
    // 2. 定义获取接口数据的action函数
    // const getUserInfo = async ({ account, password }) => {
    //   const res = await loginAPI({ account, password })
    //   userInfo.value = res.result
    //   // 合并购物车的操作
    //   await mergeCartAPI(cartStore.cartList.map(item => {
    //     return {
    //       skuId: item.skuId,
    //       selected: item.selected,
    //       count: item.count
    //     }
    //   }))
    //   cartStore.updateNewList()
    // }
    //密码登录
    const userLogin = async (data) => {
      let res = await loginAPI(data);
      if (res.code === "00000") {
        let { accessToken, refreshToken } = res.data;
        //存储toke
        userToken.value = {
          accessToken: accessToken,
          refreshToken: refreshToken,
        };
      }
      return res;
    };
	//验证码登录
	const userCodeLogin = async (data) => {
	  let res = await codeLoginAPI(data);
	  if (res.code === "00000") {
	    let { accessToken, refreshToken } = res.data;
	    //存储toke
	    userToken.value = {
	      accessToken: accessToken,
	      refreshToken: refreshToken,
	    };
	  }
	  return res;
	};
    const getUserInfo = async () => {
      let res = await getUserInfoAPI();
      if (res.code == "00000") {
        userInfo.value = res.data;
        cartStore.updateNewList();
      }
      return res;
    };
    //注册
    const userRegister = async (data) => {
      let res = await registerAPI(data);
      if (res.code === "00000") {
        let { accessToken, refreshToken } = res.data;
        //存储toke
        userToken.value = {
          accessToken: accessToken,
          refreshToken: refreshToken,
        };
      }
      return res;
    };
    // 退出时清除用户信息
    const clearUserInfo = () => {
      userInfo.value = {};
      userToken.value = {};
      // 执行清除购物车的action
      cartStore.clearCart();
    };
    // 3. 以对象的格式把state和action return
    return {
      userInfo,
      userToken,
      getUserInfo,
      clearUserInfo,
      userLogin,
	  userCodeLogin,
      getUserInfo,
      userRegister,
    };
  },
  {
    persist: true,
  }
);
